package com.zzyl.nursing.service.impl;

import java.util.Arrays;
import java.util.List;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.oss.AliyunOssUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CateringWeeklyMenuMapper;
import com.zzyl.nursing.domain.CateringWeeklyMenu;
import com.zzyl.nursing.service.ICateringWeeklyMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

/**
 * 每周食谱Service业务层处理
 *
 * @Author: alexis
 * @Date: 2024-12-30
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CateringWeeklyMenuServiceImpl extends ServiceImpl<CateringWeeklyMenuMapper, CateringWeeklyMenu> implements ICateringWeeklyMenuService {

    private final CateringWeeklyMenuMapper cateringWeeklyMenuMapper;
    private final AliyunOssUtils aliyunOssUtils;

    /**
     * 查询每周食谱
     *
     * @param id 每周食谱主键
     * @return 每周食谱
     */
    @Override
    public CateringWeeklyMenu selectCateringWeeklyMenuById(Long id) {
        CateringWeeklyMenu menu = cateringWeeklyMenuMapper.selectById(id);
        if (menu != null && StrUtil.isNotBlank(menu.getDishImage())) {
            menu.setDishImage(processImageUrl(menu.getDishImage()));
        }
        return menu;
    }

    /**
     * 查询每周食谱列表
     *
     * @param cateringWeeklyMenu 每周食谱
     * @return 每周食谱集合
     */
    @Override
    public List<CateringWeeklyMenu> selectCateringWeeklyMenuList(CateringWeeklyMenu cateringWeeklyMenu) {
        List<CateringWeeklyMenu> list = cateringWeeklyMenuMapper.selectCateringWeeklyMenuList(cateringWeeklyMenu);
        // 处理图片URL
        for (CateringWeeklyMenu menu : list) {
            if (StrUtil.isNotBlank(menu.getDishImage())) {
                menu.setDishImage(processImageUrl(menu.getDishImage()));
            }
        }
        return list;
    }

    /**
     * 新增每周食谱
     *
     * @param cateringWeeklyMenu 每周食谱
     * @return 结果
     */
    @Override
    public int insertCateringWeeklyMenu(CateringWeeklyMenu cateringWeeklyMenu) {
        // 数据校验
        validateWeeklyMenu(cateringWeeklyMenu);
        return cateringWeeklyMenuMapper.insert(cateringWeeklyMenu);
    }

    /**
     * 修改每周食谱
     *
     * @param cateringWeeklyMenu 每周食谱
     * @return 结果
     */
    @Override
    public int updateCateringWeeklyMenu(CateringWeeklyMenu cateringWeeklyMenu) {
        // 数据校验
        validateWeeklyMenu(cateringWeeklyMenu);
        return cateringWeeklyMenuMapper.updateById(cateringWeeklyMenu);
    }

    /**
     * 批量删除每周食谱
     *
     * @param ids 需要删除的每周食谱主键集合
     * @return 结果
     */
    @Override
    public int deleteCateringWeeklyMenuByIds(Long[] ids) {
        return cateringWeeklyMenuMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除每周食谱信息
     *
     * @param id 每周食谱主键
     * @return 结果
     */
    @Override
    public int deleteCateringWeeklyMenuById(Long id) {
        return cateringWeeklyMenuMapper.deleteById(id);
    }

    /**
     * 根据日期范围和餐次查询食谱
     *
     * @param cateringWeeklyMenu 查询条件
     * @return 每周食谱集合
     */
    @Override
    public List<CateringWeeklyMenu> selectWeeklyMenuByDateRange(CateringWeeklyMenu cateringWeeklyMenu) {
        List<CateringWeeklyMenu> list = cateringWeeklyMenuMapper.selectWeeklyMenuByDateRange(cateringWeeklyMenu);
        // 处理图片URL
        for (CateringWeeklyMenu menu : list) {
            if (StrUtil.isNotBlank(menu.getDishImage())) {
                menu.setDishImage(processImageUrl(menu.getDishImage()));
            }
        }
        return list;
    }

    /**
     * 上传菜品图片
     *
     * @param file 图片文件
     * @return 上传结果
     */
    @Override
    public AjaxResult uploadDishImage(MultipartFile file) {
        try {
            if (file == null || file.isEmpty()) {
                return AjaxResult.error("请选择要上传的图片");
            }

            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !isValidImageFile(originalFilename)) {
                return AjaxResult.error("只支持jpg、jpeg、png、gif格式的图片");
            }

            // 检查文件大小（限制为5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return AjaxResult.error("图片大小不能超过5MB");
            }

            // 上传到阿里云OSS
            String imageUrl = aliyunOssUtils.uploadFile(file);
            if (StrUtil.isBlank(imageUrl)) {
                return AjaxResult.error("图片上传失败");
            }

            return AjaxResult.success("图片上传成功", imageUrl);
        } catch (Exception e) {
            log.error("上传菜品图片失败", e);
            return AjaxResult.error("图片上传失败：" + e.getMessage());
        }
    }

    /**
     * 处理图片URL
     */
    @Override
    public String processImageUrl(String imageUrl) {
        if (StrUtil.isBlank(imageUrl)) {
            return imageUrl;
        }
        // 如果已经是完整URL，直接返回
        if (imageUrl.startsWith("http://") || imageUrl.startsWith("https://")) {
            return imageUrl;
        }
        // 否则直接返回，因为uploadFile已经返回完整URL
        return imageUrl;
    }

    /**
     * 验证图片文件格式
     */
    private boolean isValidImageFile(String filename) {
        String lowerCaseFilename = filename.toLowerCase();
        return lowerCaseFilename.endsWith(".jpg") || 
               lowerCaseFilename.endsWith(".jpeg") || 
               lowerCaseFilename.endsWith(".png") || 
               lowerCaseFilename.endsWith(".gif");
    }

    /**
     * 数据校验
     */
    private void validateWeeklyMenu(CateringWeeklyMenu cateringWeeklyMenu) {
        if (cateringWeeklyMenu.getMenuDate() == null) {
            throw new RuntimeException("日期不能为空");
        }

        if (cateringWeeklyMenu.getMealType() == null) {
            throw new RuntimeException("餐次类型不能为空");
        }

        if (cateringWeeklyMenu.getMealType() < 1 || cateringWeeklyMenu.getMealType() > 4) {
            throw new RuntimeException("餐次类型不正确（1：早餐，2：午餐，3：晚餐，4：加餐）");
        }

        if (StrUtil.isBlank(cateringWeeklyMenu.getDishName())) {
            throw new RuntimeException("菜品名称不能为空");
        }

        if (StrUtil.isBlank(cateringWeeklyMenu.getIngredients())) {
            throw new RuntimeException("食材不能为空");
        }

        if (cateringWeeklyMenu.getStatus() == null) {
            cateringWeeklyMenu.setStatus(1); // 默认启用
        }
    }
} 